<template>
  <div class="app-container">
    <!-- 高级查询 -->
    <el-form v-show="searchVisible" ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item label="区域名称:">
        <el-input v-model="queryParams.regionName" size="small" placeholder="请输入区域名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="区域类型:">
        <el-select v-model="queryParams.regionType" placeholder="请选择区域类型" clearable size="small">
          <el-option v-for="option in options.regionTypeOptions" :key="option.dictValueCode" :label="option.dictValueName" :value="option.dictValueCode" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermission="['system:region:insert']" type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermission="['system:region:update']" type="success" icon="el-icon-edit" size="mini" :disabled="isSingle" @click="handleEdit">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermission="['system:region:delete']" type="danger" icon="el-icon-delete" size="mini" :disabled="isMultiple" @click="handleRemove">删除</el-button>
      </el-col>
      <right-toolbar :show-search.sync="searchVisible" @queryTable="handleQuery" />
    </el-row>

    <!-- 数据列表 -->
    <el-table v-loading="loading" row-key="id" :data="regionList" :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column label="区域编码" align="left" prop="id" />
      <el-table-column label="区域名称" align="left" prop="regionName" />
      <el-table-column label="区域全称" align="left" prop="regionFullName" />
      <el-table-column label="区域类型" align="center" prop="regionType">
        <template slot-scope="scope">
          <span>{{ regionTypeFormat(scope.row) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="treeSort" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-hasPermission="['system:region:update']" size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">修改</el-button>
          <el-button v-hasPermission="['system:region:delete']" size="mini" type="text" icon="el-icon-delete" @click="handleRemove(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/修改对话框 -->
    <el-dialog :title="regionFormDialog.title" :visible.sync="regionFormDialog.visible" :close-on-click-modal="false" :before-close="resetRegionFormDialog" width="500px" append-to-body>
      <el-form ref="regionForm" :model="regionFormData" :rules="regionFormRules" label-width="80px">
        <el-col :span="24">
          <el-form-item label="上级区域">
            <treeselect v-model="regionFormData.pid" :options="options.regionOptions" :normalizer="normalizer" :show-count="true" placeholder="选择上级区域" />
          </el-form-item>
        </el-col>
        <el-form-item label="区域编码" prop="id">
          <el-input v-model="regionFormData.id" placeholder="请输入区域编码" />
        </el-form-item>
        <el-form-item label="区域名称" prop="regionName">
          <el-input v-model="regionFormData.regionName" placeholder="请输入区域名称" />
        </el-form-item>
        <el-form-item label="区域全称" prop="regionFullName">
          <el-input v-model="regionFormData.regionFullName" placeholder="请输入区域全称" />
        </el-form-item>
        <el-form-item label="区域类型" prop="regionType">
          <el-select v-model="regionFormData.regionType" style="width: 380px" clearable placeholder="请选择区域类型">
            <el-option v-for="option in options.regionTypeOptions" :key="option.dictValueCode" :label="option.dictValueName" :value="option.dictValueCode" />
          </el-select>
        </el-form-item>
        <el-form-item label="显示排序" prop="treeSort">
          <el-input-number v-model="regionFormData.treeSort" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="regionFormData.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmRegionFormDialog">确 定</el-button>
        <el-button @click="resetRegionFormDialog">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import RegionApi from '@/api/system/RegionApi'
import DictValueApi from '@/api/system/DictValueApi'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

const defaultRegionFormData = {
  ancestorIds: null,
  ancestorNames: null,
  regionName: null,
  regionFullName: null,
  regionType: null,
  treeLevel: null,
  isLeaf: null,
  treeSort: null
}
export default {
  name: 'RegionList',
  components: { Treeselect },
  data() {
    return {
      options: {
        regionTypeOptions: [], // 区域类型字典
        regionOptions: []
      },
      queryParams: {
        regionName: null,
        regionType: null,
        isValid: this.$constant.Y
      },
      regionList: [],
      regionFormDialog: {
        title: '',
        visible: false,
        type: null
      },
      regionFormData: Object.assign({}, defaultRegionFormData),
      regionFormRules: {
        id: [{ required: true, message: '区域编码不能为空', trigger: 'blur' }],
        regionName: [{ required: true, message: '区域名称不能为空', trigger: 'blur' }]
      },
      loading: true,
      searchVisible: true,
      isSingle: true,
      isMultiple: true
    }
  },
  created() {
    this.handleQuery()
    this.loadOptions()
  },
  methods: {
    loadOptions() {
      DictValueApi.list({ dictCode: 'sys_region_type' }).then(response => {
        this.options.regionTypeOptions = response.data
      })
    },
    handleAdd(row) {
      this.regionFormDialog.type = 'add'
      this.openRegionFormDialog(row.id)
    },
    handleRemove(row) {
      this.$confirm('是否确认删除数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return RegionApi.remove(row.id)
      }).then(() => {
        this.handleQuery()
        this.$message.success('删除成功')
      })
    },
    handleEdit(row) {
      this.regionFormDialog.type = 'edit'
      this.openRegionFormDialog(row.id)
    },
    handleQuery() {
      this.loading = true
      RegionApi.list(this.queryParams).then(response => {
        this.regionList = this.$common.list2Tree(response.data)
        this.loading = false
      }, () => {
        this.loading = false
      })
      RegionApi.treeSelect().then(response => {
        const root = { id: 0, label: '主类目', children: [] }
        root.children = response.data
        this.options.regionOptions.push(root)
      })
    },
    handleExport() {
      this.$confirm('是否确认导出数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return RegionApi.exportData(this.queryParams)
      }).then(response => {
        this.$common.download(response.data)
      })
    },
    openRegionFormDialog(id) {
      this.regionFormDialog.visible = true
      if (this.regionFormDialog.type === 'add') {
        this.regionFormDialog.title = '区域-添加'
        if (id) {
          this.regionFormData.pid = id
        } else {
          this.regionFormData.pid = 0
        }
      }
      if (this.regionFormDialog.type === 'edit') {
        this.regionFormDialog.title = '区域-修改'
        RegionApi.get(id).then(response => {
          this.regionFormData = response.data
        })
      }
    },
    confirmRegionFormDialog() {
      this.$refs['regionForm'].validate(valid => {
        if (valid) {
          if (this.regionFormDialog.type === 'add') {
            RegionApi.add(this.regionFormData).then(response => {
              this.$message.success('添加成功')
              this.resetRegionFormDialog()
              this.handleQuery()
            })
          }
          if (this.regionFormDialog.type === 'edit') {
            RegionApi.edit(this.regionFormData).then(response => {
              this.$message.success('修改成功')
              this.resetRegionFormDialog()
              this.handleQuery()
            })
          }
        }
      })
    },
    resetRegionFormDialog() {
      this.regionFormDialog = {
        title: '',
        visible: false
      }
      this.regionFormData = Object.assign({}, defaultRegionFormData)
      this.resetForm('regionForm')
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return node
    },
    // 区域类型字典
    regionTypeFormat(row) {
      return this.$common.getDictValueName(this.options.regionTypeOptions, row.regionType)
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    }
  }
}
</script>
